package com.powernobug.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Integer[].class)
public class IntegerJsonArrayTypeHandler extends BaseTypeHandler<Integer[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        // Convert Integer[] to a comma-separated string
        StringBuilder sb = new StringBuilder();
        for (int index = 0; index < parameter.length; index++) {
            sb.append(parameter[index]);
            if (index < parameter.length - 1) {
                sb.append(",");
            }
        }
        ps.setString(i, sb.toString());
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // Convert the comma-separated string back to Integer[]
        String columnValue = rs.getString(columnName);
        return parseStringToIntArray(columnValue);
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // Convert the comma-separated string back to Integer[]
        String columnValue = rs.getString(columnIndex);
        return parseStringToIntArray(columnValue);
    }

    @Override
    public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // Convert the comma-separated string back to Integer[]
        String columnValue = cs.getString(columnIndex);
        return parseStringToIntArray(columnValue);
    }

    private Integer[] parseStringToIntArray(String columnValue) {
        if (columnValue == null || columnValue.isEmpty()) {
            return new Integer[0];
        }
        // 去除方括号并将字符串按逗号分割
        columnValue = columnValue.replaceAll("[\\[\\]\\s]", "");
        String[] parts = columnValue.split(",");
        Integer[] result = new Integer[parts.length];
        for (int i = 0; i < parts.length; i++) {
            result[i] = Integer.parseInt(parts[i]);
        }
        return result;
    }
}
